/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */

import axios from 'axios'



const request =axios.create({
  timeout: 1000 * 60 * 60 * 24,
})
request.interceptors.response.use((response) => {
  return response;
}, () => {

})

export default request;

import type {
  RequestOptionsWithResponse,
  RequestResponse,
  RequestOptionsWithoutResponse,
  RequestOptionsInit,
  RequestMethod,
} from 'umi-request';
import { extend } from 'umi-request';
import storage from './storage';
import { isBrowser } from 'umi';
import { TOKEN } from '@/common/const';
import { message } from 'antd';
import { baseurl } from '../../config/server.config';
// import { stringify } from 'querystring';
// import { getToken } from './authority';
// import { Redirect } from 'umi';

type ExtraOptions = {
  skipErrorHandler?: boolean;
  loading?: boolean;
  /**
   * 文件上传的xhr实例对象引用
   */
  xhrRef?: { xhr?: XMLHttpRequest };
};
export type MyRequestOptionsWithResponse = RequestOptionsWithResponse & ExtraOptions;
export type MyRequestOptionsWithoutResponse = RequestOptionsWithoutResponse & ExtraOptions;
export type MyRequestOptionsInit = RequestOptionsInit & ExtraOptions;

export interface RequestMethodInUmi<R = false> {
  <T = any>(url: string, options: MyRequestOptionsWithResponse): Promise<RequestResponse<T>>;
  <T = any>(url: string, options: MyRequestOptionsWithoutResponse): Promise<T>;
  <T = any>(url: string, options?: MyRequestOptionsInit): R extends true
    ? Promise<RequestResponse<T>>
    : Promise<T>;
}

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const showErrorMessage = (text) => {
  if (isBrowser()) {
    message.error(text);
  }
};

/**
 * 异常处理程序
 */
const errorHandler = (error) => {
  const { response, request } = error;
  const { skipErrorHandler } = request.options;
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    if (!skipErrorHandler) {
      showErrorMessage(`${errorText}, 状态码： ${status}，url: ${url}`);
    }
  } else if (!response) {
    !skipErrorHandler && showErrorMessage('网络异常');
  }
  return { code: response?.status || -999 };
};

/**
 *
 * 判断是绝对路径
 */
const isAbsoluteUrl = (url) => {
  return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};

/**
 * 异常code处理
 * @param code
 */
const errorCodeHandler = (code) => {
  if (code === 403 || code === 401) {
    //goLogin('push');
    // window.location.href = '/login';
  }
};

let requestMethodInstance: RequestMethod;
/**
 * 配置request请求时的默认参数
 */
const getRequestMethod = () => {
  // request method 已经实例化
  if (requestMethodInstance) {
    return requestMethodInstance;
  }

  requestMethodInstance = extend({
    method: 'post',
    errorHandler, // 默认错误处理
    timeout: 1000 * 60 * 60 * 24, // 超时时间,
    credentials: 'include', // 默认请求是否带上cookie
  });
  // 注册内核中间件

  /**
   * 请求前加个loading
   */
  requestMethodInstance.interceptors.request.use((url, options: any) => {
    let headers = {
      ...(options?.headers || {}),
    };

    let newUrl = url;
    // 客户端
    if (isBrowser()) {
      const token = storage.get(TOKEN) || {};
      headers = {
        ...headers,
        Authorization: `Bearer ${token?.access_token}`, // token
        token: token?.access_token,
      };
    }
    // 服务端
    else {
      newUrl = isAbsoluteUrl(url) ? url : `${baseurl}${url}`;
    }
    return {
      url: newUrl,
      options: {
        responseType: 'json',
        ...options,
        headers,
      },
    };
  });

  // requestMethodInstance.interceptors.response.use(async (response, options) => {
  //   if (options.responseType === 'json') {
  //     const data = await response.clone().json();
  //     if (
  //       (data.code > 299 || data.code < 200) &&
  //       (options as MyRequestOptionsWithResponse).skipErrorHandler !== true
  //     ) {
  //     }
  //   }
  //   return response;
  // });
  requestMethodInstance.use(progressMiddleware, { core: true });
  return requestMethodInstance;
};

const request2: RequestMethodInUmi = (url: any, options: any) => {
  const requestMethod = getRequestMethod();
  return requestMethod(url, options);
};

function ajaxRequest(url, options) {
  return new Promise(function (resolve, reject) {
    var _a, _b, _c;
    const method = (_a = options.method) != null ? _a : 'get';
    const headers = (_b = options.headers) != null ? _b : {};
    const { onReqProgress, onResProgress, credentials, responseType, body, parseResponse } =
      options;
    const xhr = new XMLHttpRequest();
    if (options.xhrRef) {
      options.xhrRef.xhr = xhr;
    }
    switch (credentials) {
      case 'include': {
        xhr.withCredentials = true;
        break;
      }
      case 'omit': {
        xhr.withCredentials = false;
        break;
      }
    }
    if (responseType !== 'formData') {
      xhr.responseType =
        (_c = responseType == null ? void 0 : responseType.toLowerCase()) != null ? _c : 'json';
    }
    xhr.open(method, url);
    for (const [key, value] of Object.entries(headers)) {
      xhr.setRequestHeader(key, value);
    }
    xhr.onload = (e) => {
      resolve(xhr);
    };
    xhr.onerror = reject;
    if (xhr.upload && onReqProgress) {
      xhr.upload.onprogress = onReqProgress;
    }
    if (onResProgress) {
      xhr.onprogress = onResProgress;
    }
    xhr.send(body);
  });
}

const progressMiddleware = async function (ctx, next) {
  const { url, options } = ctx.req;
  if (!(options.onReqProgress || options.onResProgress)) {
    await next();
    return;
  }
  options.__umiRequestCoreType__ = 'ajaxRequest';
  const response = await ajaxRequest(url, options);
  ctx.res = response;
  await next();

  return response;
};


